package com.gh.blog.service;

import com.gh.blog.dto.ScoreDTO;
import com.gh.blog.dto.StudentDetailDTO;
import com.gh.blog.dto.StudentInfoDTO;
import com.gh.blog.entity.Course;
import com.gh.blog.entity.Score;
import com.gh.blog.entity.Student;
import com.gh.blog.mapper.CourseMapper;
import com.gh.blog.mapper.ScoreMapper;
import com.gh.blog.mapper.StuMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Fawn
 * @Date 2020/8/11 23:00
 * @Version 1.0
 **/
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class StuServiceImpl implements StuService {

    private final StuMapper stuMapper;
    private final ScoreMapper scoreMapper;
    private final CourseMapper courseMapper;

    @Override
    public List<Student> findAll() {
        return stuMapper.findAll();
    }

    @Override
    public PageInfo<Student> findByPage(Integer current, Integer size){
        PageHelper.startPage(current, size);
        List<Student> students = stuMapper.findByPage();
        return new PageInfo<Student>(students);
    }

    @Override
    public StudentDetailDTO findDetail(String no) {
        // 查询学生
        StudentDetailDTO studentDetail = new StudentDetailDTO().convertFrom(stuMapper.findByNo(no));

        // 查询学生全部成绩
        List<ScoreDTO> scores = new ArrayList<>();
        for (Score item : scoreMapper.listByStudentNo(no)) {
            ScoreDTO score = new ScoreDTO().convertFrom(item);

            // 查询成绩对应课程
            Course course = courseMapper.getByCode(item.getCourseNo());
            score.setCourse(course);

            scores.add(score);
        }

        studentDetail.setScores(scores);
        return studentDetail;
    }

    @Override
    public StudentInfoDTO findStuInfo(String no) {

        StudentInfoDTO studentInfo=new StudentInfoDTO();
        List<Student> list = new ArrayList<>();
        for (Score item : scoreMapper.listByCourseNo(no)) {
            studentInfo.convertFrom(item);

            Student student = stuMapper.findByNo(item.getStudentNo());

            list.add(student);

        }
        studentInfo.setStudent(list);
        return studentInfo;
    }
}
